package com.guigu.pd.oms.service.impl;

import com.guigu.pd.oms.dao.RuleDao;

import com.guigu.pd.oms.entity.RuleEntity;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author lizongyi
 * @date 2022/7/25
 * @Note 重新加载数据库中的规则，创建Drools相关对象
 */
@Service
public class ReloadDroolsRulesService {


    //全局唯一容器对象，用于创建Session操作Drools
    public static KieContainer kieContainer;

    @Autowired
    private RuleDao ruleMapper;

    /**
     * 查询数据库中所有规则
     * @return
     */
    private List<RuleEntity> loadRules() {
        List<RuleEntity> rules = ruleMapper.selectList(null);
        return rules;
    }



    /**
     * 重新创建KieContainer对象
     */
    public void reload() {
        KieContainer kieContainer = loadContainerFromString(loadRules());
        this.kieContainer = kieContainer;
    }


    /**
     * 根据规则内容创建KieContainer对象
     * @param rules
     * @return
     */
    public KieContainer loadContainerFromString(List<RuleEntity> rules) {
        //long startTime = System.currentTimeMillis();
        //KieServices ks = KieServices.Factory.get();
        //KieRepository kr = ks.getRepository();
        //KieFileSystem kfs = ks.newKieFileSystem(); //文件系统对象
        //
        //for (RuleEntity rule : rules) {
        //    String drl = rule.getContent();
        //    kfs.write("src/main/resources/" + drl.hashCode() + ".drl", drl);
        //}
        //
        //KieBuilder kb = ks.newKieBuilder(kfs);
        //kb.buildAll();
        //
        //if (kb.getResults().hasMessages(Message.Level.ERROR)) {
        //    throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
        //}
        //
        //long endTime = System.currentTimeMillis();
        //System.out.println("Time to build rules : " + (endTime - startTime) + " ms");
        //startTime = System.currentTimeMillis();
        //KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
        //endTime = System.currentTimeMillis();
        //System.out.println("Time to load container: " + (endTime - startTime) + " ms");
        //return kContainer;

        KieServices ks = KieServices.Factory.get();
        KieRepository kr = ks.getRepository();
        KieFileSystem kfs = ks.newKieFileSystem();

        for (RuleEntity rule : rules) {
            String drl = rule.getContent();
            kfs.write("src/main/resources/" + drl.hashCode() + ".drl", drl);
        }

        KieBuilder kb = ks.newKieBuilder(kfs);

        kb.buildAll();

        KieContainer kieContainer = ks.newKieContainer(kr.getDefaultReleaseId());


        return  kieContainer;
    }

}
